<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="员工姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入员工姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="薪资月份" prop="salaryMonth">
        <el-input v-model="queryParams.salaryMonth" placeholder="例如 2025-07" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:salary:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:salary:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:salary:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:salary:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="salaryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工姓名" align="center" prop="userName" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="月份" align="center" prop="salaryMonth" width="120" />
      <el-table-column label="基本工资" align="center" prop="baseSalary" />
      <el-table-column label="奖金" align="center" prop="bonus" />
      <el-table-column label="津贴" align="center" prop="allowance" />
      <el-table-column label="扣款" align="center" prop="deduction" />
      <el-table-column label="个税" align="center" prop="tax" />
      <el-table-column label="实发" align="center" prop="netSalary" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:salary:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:salary:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改薪资对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入员工姓名" @blur="handleUserNameBlur" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="部门名称将自动填充" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="薪资月份" prop="salaryMonth">
              <el-input v-model="form.salaryMonth" placeholder="例如 2025-07" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本工资" prop="baseSalary">
              <el-input v-model="form.baseSalary" placeholder="请输入基本工资" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="奖金" prop="bonus">
              <el-input v-model="form.bonus" placeholder="请输入奖金" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="津贴" prop="allowance">
              <el-input v-model="form.allowance" placeholder="请输入津贴" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扣款" prop="deduction">
              <el-input v-model="form.deduction" placeholder="请输入扣款" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="个税" prop="tax">
              <el-input v-model="form.tax" placeholder="请输入个税" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实发工资" prop="netSalary">
              <el-input v-model="form.netSalary" placeholder="请输入实发工资" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSalary, getSalary, addSalary, updateSalary, delSalary } from "@/api/system/salary";
import { listUser } from "@/api/system/user";


export default {
  name: "Salary",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      salaryList: [],
      title: "",
      open: false,
      // 移除部门树选项
      // deptOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        deptName: undefined,
        salaryMonth: undefined,
        status: undefined
      },
      form: {
        salaryId: undefined,
        userId: undefined,
        userName: undefined,
        deptId: undefined,
        deptName: undefined,
        salaryMonth: undefined,
        baseSalary: undefined,
        bonus: undefined,
        allowance: undefined,
        deduction: undefined,
        tax: undefined,
        netSalary: undefined,
        status: '0',
        remark: undefined
      },
      rules: {
        userName: [ { required: true, message: "员工姓名不能为空", trigger: "blur" } ],
        salaryMonth: [ { required: true, message: "薪资月份不能为空", trigger: "blur" } ],
        baseSalary: [ { required: true, message: "基本工资不能为空", trigger: "blur" } ],
        netSalary: [ { required: true, message: "实发工资不能为空", trigger: "blur" } ]
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 根据员工姓名获取部门信息 */
    handleUserNameBlur() {
      const userName = this.form.userName;
      if (userName) {
        listUser({ userName: userName }).then(response => {
          if (response.rows && response.rows.length > 0) {
            const user = response.rows[0];
            this.$set(this.form, 'userId', user.userId);
            this.$set(this.form, 'deptId', user.deptId);
            this.$set(this.form, 'deptName', user.dept.deptName);
          } else {
            this.$modal.msgWarning("未找到该员工，请确认员工姓名是否正确");
            this.$set(this.form, 'userId', undefined);
            this.$set(this.form, 'deptId', undefined);
            this.$set(this.form, 'deptName', undefined);
          }
        }).catch(() => {
          this.$modal.msgError("查询员工信息失败");
          this.$set(this.form, 'userId', undefined);
          this.$set(this.form, 'deptId', undefined);
          this.$set(this.form, 'deptName', undefined);
        });
      } else {
        this.$set(this.form, 'userId', undefined);
        this.$set(this.form, 'deptId', undefined);
        this.$set(this.form, 'deptName', undefined);
      }
    },
    /** 查询薪资列表 */
    getList() {
      this.loading = true;
      listSalary(this.queryParams).then(res => {
        this.salaryList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        salaryId: undefined,
        userId: undefined,
        userName: undefined,
        deptId: undefined,
        deptName: undefined,
        salaryMonth: undefined,
        baseSalary: undefined,
        bonus: undefined,
        allowance: undefined,
        deduction: undefined,
        tax: undefined,
        netSalary: undefined,
        status: '0',
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮 */
    handleQuery() { this.queryParams.pageNum = 1; this.getList(); },
    /** 重置按钮 */
    resetQuery() { this.resetForm("queryForm"); this.handleQuery(); },
    // 多选
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.salaryId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增 */
    handleAdd() {
      this.reset();
      // 移除每次新增前获取最新部门树
      // this.getTreeselect();
      this.open = true;
      this.title = "添加薪资";
    },
    /** 修改 */
    handleUpdate(row) {
      this.reset();
      const id = row.salaryId || this.ids;
      getSalary(id).then(res => {
        this.form = res.data;
        this.open = true;
        this.title = "修改薪资";
      });
    },
    /** 提交 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;
        const req = this.form.salaryId !== undefined ? updateSalary(this.form) : addSalary(this.form);
        req.then(() => { this.$modal.msgSuccess(this.form.salaryId ? "修改成功" : "新增成功"); this.open = false; this.getList(); });
      });
    },
    /** 删除 */
    handleDelete(row) {
      const ids = row.salaryId || this.ids;
      this.$modal.confirm('是否确认删除薪资编号为"' + ids + '"的数据项？')
        .then(() => delSalary(ids))
        .then(() => { this.getList(); this.$modal.msgSuccess("删除成功"); })
        .catch(() => {});
    },
    /** 导出 */
    handleExport() {
      this.download('system/salary/export', { ...this.queryParams }, `salary_${new Date().getTime()}.xlsx`);
    }
  }
}
</script>

<style scoped>
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
}
</style>
